package com.vnaloha.common.dao;

import java.util.Collection;
import java.util.List;

import org.hibernate.HibernateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.vnaloha.common.model.User;
import com.vnaloha.util.CustomHibernateDaoSupport;

@Repository
public class UserDAOImpl extends CustomHibernateDaoSupport implements UserDAO {

	private Logger logger = LoggerFactory.getLogger(UserDAOImpl.class);

	@Override
	public void addUser(User user) {
		getHibernateTemplate().save(user);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> listUser() {
		List<User> users = null;
		try {
			users = (List<User>) getHibernateTemplate().find(" from User order by id desc");
		} catch (HibernateException e) {
			logger.error("Error when get list user " + e, e);
		}
		return users;
	}

	@Override
	public void removeUser(Integer id) {
		User user = (User) getHibernateTemplate().get(User.class, id);
		if (null != user) {
			getHibernateTemplate().delete(user);
		}
	}

	@Override
	public User getById(Integer id) {
		User user = (User) getHibernateTemplate().get(User.class, id);
		return user;
	}

	@Override
	public void update(User user) {
		getHibernateTemplate().update(user);
	}

	@SuppressWarnings("unchecked")
	@Override
	public User getUserByUsername(String userName) {
		String queryString = "from User u where (u.username = :username)";
		
		User user = new User();
		User userBean = new User();
		userBean.setUsername(userName);
		Collection<User> users = getHibernateTemplate().findByValueBean(queryString, userBean);
		
		if((users != null) && (!users.isEmpty())) {
			user = users.iterator().next();
		}
		
		return user;
	}

}
